package com.chinasoft.maysham.manager.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public final class JacksonUtil {

    private JacksonUtil() {
    }

    public static <T> T toObj(String content, Class<T> tClass) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            return objectMapper.readValue(content, tClass);
        } catch (IOException e) {
            return null;
        }
    }

    public static <T> T toObj(String content, TypeReference<T> typeReference) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            return objectMapper.readValue(content, typeReference);
        } catch (IOException e) {
            return null;
        }
    }

    public static String toString(Object o) {
        try {
            return getMapper().writeValueAsString(o);
        } catch (JsonProcessingException e) {
            return null;
        }
    }

    private static ObjectMapper getMapper() {
        return new ObjectMapper();
    }
}
